package com.edu.tool.controller.signup;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.common.util.SimpleStringUtil;
import com.edu.tool.annotation.NotCheckToken;
import com.edu.tool.bc.SysBcDef;
import com.edu.tool.bc.SysBusComp;
import com.edu.tool.bean.Record;
import com.edu.tool.bean.linkbeans.user.SysEmpResponsiblity;
import com.edu.tool.bean.uidef.SysApplet;
import com.edu.tool.bean.user.*;
import com.edu.tool.constant.MsgConstant;
import com.edu.tool.exception.captcha.CaptchaException;
import com.edu.tool.mapper.bc.SysBCMapper;
import com.edu.tool.mapper.conf.SysTenantDictConfMapper;
import com.edu.tool.mapper.links.user.SysEmpResponsiblityMapper;
import com.edu.tool.mapper.uidef.SysAppletMapper;
import com.edu.tool.mapper.user.*;
import com.edu.tool.service.user.SysCaptchaService;
import com.edu.tool.service.user.SysLoginTokenService;
import com.edu.tool.service.sms.SysSmsService;
import com.edu.tool.service.user.SysTenantService;
import com.edu.tool.util.IpUtil;
import com.edu.tool.util.MsgUtil;

import freemarker.template.utility.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping(value = "/api/v1")
@RestController
@Api(value="对象定义Controller")
public class SysSignUpController {

    @Autowired
    private SysTenantService tenantService;

    //@Autowired
    //private SysAuthTokenMapper authTokenMapper;

    @Autowired
    private SysTenantTrialMapper tenantTrialMapper;

    @Autowired
    private SysTenantRegisterMapper tenantRegisterMapper;

    @Autowired
    private SysTenantDictConfMapper tenantDictConfMapper;

    @Autowired
    private SysEmployeeMapper employeeMapper;

    @Autowired
    private SysReponsibilityMapper reponsibilityMapper;

    @Autowired
    private SysEmpResponsiblityMapper empResponsiblityMapper;

    @Autowired
    private SysCaptchaService captchaService;

    @Autowired
    private SysSmsService smsService;

    @Autowired
    private SysLoginTokenService loginTokenService;




    Logger logger = LoggerFactory.getLogger(SysSignUpController.class);

//    @PostMapping("/signup")
//    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
//    public ModelMap signup (@RequestBody SysUser user,
//                            @RequestParam(value="openId",required = false) String openid,
//                            @RequestParam String code,
//                            @RequestParam String hashcode,
//                            @RequestParam String company) {
//
//    }
//
//
    @RequestMapping(value = "/authcode", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "get trial authcode", notes = "get trial authcode")
    @NotCheckToken
    public Object getAuthCode(HttpServletRequest request,
                               @RequestParam String phone,
                               @RequestParam String captcha,
                               @RequestParam String captchaToken,
                               @RequestParam String bizType) {
        logger.info("get authcode");

        if(StringUtils.isEmpty(phone))
        {
           return  MsgUtil.retMsgMap(MsgConstant.EMPTY_PHONE_CODE);

        }
        try {
            QueryWrapper<SysTenantRegister> tenantRegisterQR = new QueryWrapper<>();
            tenantRegisterQR.lambda().eq(SysTenantRegister::getPhone, phone);
            SysTenantRegister record = tenantRegisterMapper.selectOne(tenantRegisterQR);
            if (record != null) {
                return MsgUtil.retMsgMap(MsgConstant.REGISTERED_PHONE_CODE);
            }

            if(bizType.equalsIgnoreCase("Trial")) {
                QueryWrapper<SysTenantTrial> tenantTrialQR = new QueryWrapper<>();
                tenantTrialQR.lambda().eq(SysTenantTrial::getPhone, phone);
                SysTenantTrial tenantTrial = tenantTrialMapper.selectOne(tenantTrialQR);
                if (tenantTrial != null) {
                    return MsgUtil.retMsgMap(MsgConstant.REGISTERED_PHONE_CODE);
                }
            }


            //校验图形验证码
            captchaService.verify(null, captchaToken, captcha);
            Map result = null;
            if(bizType.equalsIgnoreCase("Trial")) {
                result = smsService.getAuthCode(153, phone, "MSG_VERIFY_TRIAL");
            }
            else
            {
                result = smsService.getAuthCode(153, phone, "MSG_VERIFY_REGISTER");
            }

            return MsgUtil.retMap("authobj",result);
        }catch(CaptchaException cte){
            return MsgUtil.retMsgMap(MsgConstant.INVALID_CAPTCHACODE,cte.getMessage());
        }

    }

    @RequestMapping(value = "/trialuser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "trialuser", notes = "申请试用")
    @NotCheckToken

    public Object trialuser(HttpServletRequest request,
                        @RequestParam String authToken,
                        @RequestParam String phoneCode,
                        @RequestParam String name,
                        @RequestParam(required = false) String mail,
                        @RequestParam String shortName,
                        @RequestParam String industry,
                        @RequestParam String channel) {
        String ipAddress = IpUtil.getIpAddr(request);

        return tenantService.createTrialUser(ipAddress,
                authToken,
                phoneCode,
                name,
                mail,
                shortName,
                industry,
                channel);

    }


    @RequestMapping(value = "/registeruser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "registeruser", notes = "申请试用")
    @NotCheckToken

    public Object registeruser(HttpServletRequest request,
                               @RequestParam String authToken,
                               @RequestParam String phoneCode,
                               @RequestParam String pwd,
                               @RequestParam String companyName,
                               @RequestParam Integer template,
                               @RequestParam String domain,
                               @RequestParam String employeeName,
                               @RequestParam(required=false) String openId,
                               @RequestParam(required=false) Integer tenantType) {
        String ipAddress = IpUtil.getIpAddr(request);

        return tenantService.createRegisterUser(   ipAddress,authToken,
                  phoneCode,
                  pwd,
                  companyName,
                  template,
                  domain,
                  employeeName,
                  openId,
                  tenantType);

    }

    @RequestMapping(value = "/dictconf", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "dictconf", notes = "添加字典")
    @NotCheckToken
    public Object dictconf(HttpServletRequest request,
                           @RequestParam String dictId,
                           @RequestParam String dictName,
                           @RequestParam String dictType,
                           @RequestParam String dictValue,
                           @RequestParam String remark

    )
    {
        SysTenantDictConf tenantDictConf = new SysTenantDictConf();
        tenantDictConf.setDictId(dictId);
        tenantDictConf.setDictIdName(dictName);
        tenantDictConf.setDictType(dictType);
        tenantDictConf.setDictValue(dictValue);
        tenantDictConf.setRemark(remark);
        String uuid = UUID.randomUUID().toString();
        tenantDictConf.setUuid(uuid);

        tenantDictConfMapper.insert(tenantDictConf);

        return MsgUtil.retMsgMap(MsgConstant.SUCCESS_RET,"字典创建成功。");
    }


}
